package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * 全局Id生成器
 */
@Component
public class RedisIdWork {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    // 起始时间戳
    private static final long BEGIN_TIMESTAMP = 1640995200L;
    // 序列号位数
    private static final int COUNT_BITS = 32;
    public long nextId(String keyPrefix) {
        //1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);//当前秒数
        long timestamp = nowSecond - BEGIN_TIMESTAMP;
        //2.生成序列号
        Long increment = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" +
                now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd")));//每天日期的key,订单默认每次自增长1
        //3.拼接返回
        return timestamp << COUNT_BITS | increment;//此处的拼接默认是转成2进制进行位运算，之后再转成十进制
    }
}
